package com.dyna.core.config;

import cn.hutool.core.util.StrUtil;
import com.dyna.constants.StringPool;
import com.dyna.constants.TokenConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 远程调用携带请求头
 * @author Admin
 */

@Configuration
@EnableFeignClients
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            //添加token
            String authHeader = request.getHeader(TokenConstant.AUTHORIZATION);
            if (StrUtil.isNotBlank(authHeader) && !StringPool.NULL.equals(authHeader)) {
                requestTemplate.header(TokenConstant.AUTHORIZATION, authHeader);
            }
        }
    }
}